define([
  "jquery",
  "bootstrap",
  "backend",
  "table",
  "form",
  "bootstrap-select-lang",
  "selectpage",
], function ($, undefined, Backend, Table, Form, undefined, undefined) {
  var Controller = {
    index: function () {
      Table.api.init({
        extend: {
          index_url: "fastflow/flow/flow/index" + location.search,
          add_url: "fastflow/flow/flow/add",
          edit_url: "fastflow/flow/flow/edit",
          del_url: "fastflow/flow/flow/del",
          multi_url: "fastflow/flow/flow/multi",
          import_url: "fastflow/flow/flow/import",
          table: "wf_flow",
        },
      });

      var table = $("#table");

      table.on("post-common-search.bs.table", function (event, table) {
        var form = $("form", table.$commonsearch);
        $("input[name='createuser_id']", form)
          .addClass("selectpage")
          .data("source", "fastflow/flow/flow/getSelectpageWorkers?scope=1")
          .data("primaryKey", "id")
          .data("field", "createuser_id")
          .data("orderBy", "id asc");
        Form.events.selectpage(form);
      });

      table.bootstrapTable({
        url: $.fn.bootstrapTable.defaults.extend.index_url,
        pk: "id",
        sortName: "id",
        rowStyle: function (row, index) {
          return {
            css: {
              height: "60px",
            },
          };
        },
        columns: [
          [
            { field: "id", title: __("Id"), sortable: true },
            { field: "name", title: __("Name"), operate: "LIKE" },
            {
              field: "bill_name",
              title: __("BillName"),
              formatter: Controller.api.formatter.normal,
            },
            {
              field: "bill",
              title: __("Bill"),
              formatter: Table.api.formatter.normal,
            },
            {
              field: "description",
              title: __("Description"),
              operate: "LIKE",
              formatter: Table.api.formatter.content,
            },
            {
              field: "createuser_id",
              title: __("CreateuserId"),
              formatter: Table.api.formatter.search,
              visible: false,
            },
            { field: "initiator", title: __("Initiator"), operate: false },
            {
              field: "createtime",
              title: __("Createtime"),
              operate: "RANGE",
              addclass: "datetimerange",
              autocomplete: false,
              formatter: Table.api.formatter.datetime,
            },
            {
              field: "status",
              title: __("Status"),
              searchList: { 0: __("Status 0"), 1: __("Status 1") },
              formatter: Controller.api.formatter.status,
              events: Controller.api.events.status,
              custom: { 0: "success", 1: "danger" },
            },
            {
              field: "",
              title: __("Designer"),
              operate: false,
              table: table,
              events: Controller.api.events.opendesigner,
              formatter: Controller.api.formatter.designerbtn,
            },
            {
              field: "",
              title: __("FlowAuth"),
              operate: false,
              formatter: Controller.api.formatter.flowauth,
            },
            {
              field: "operate",
              title: __("EDIT"),
              table: table,
              events: Table.api.events.operate,
              formatter: Table.api.formatter.operate,
            },
            {
              field: "remark",
              title: __("Remark"),
              operate: false,
              formatter: Table.api.formatter.content,
            },
          ],
        ],
      });

      Table.api.bindevent(table);

      $("body", document).on("keyup", function (e) {
        if (e.which === 27) {
          return false;
        }
      });
    },
    add: function () {
      Form.api.bindevent($("form[role=form]"));
    },
    edit: function () {
      Form.api.bindevent($("form[role=form]"));
    },
    designer: function () {
      if ($(window).width() < 700) {
        $("body").html(
          '<div class="alert alert-danger">请使用电脑进行流程设计或确保设计器窗口宽度大于700像素</div>'
        );
        return;
      }
      require(["fastflow-fastflow"], function (fastflow) {
        fastflow.run(
          Config.flow.graph,
          Config.flow.id,
          (config = { saveAction: "fastflow/flow/Flow/saveGraph" })
        );
        $(document).on(
          "fa.event.appendfieldlist",
          ".btn-append",
          function (e, obj) {
            Form.events.selectpage(obj);
            fastflow.createStepSelectOption();
          }
        );
      });

      Form.api.bindevent($("form[role=form]"));
      $("#c-worker").data("params", function (obj) {
        return { scope: $("#c-scope").val() };
      });
    },
    detail: function () {
      //调整窗口大小---
      var footer = $(".footer");
      $(".layui-layer-content", parent.document).after(footer);
      footer.css("display", "block");
      var dialogHeight = $(".layui-layer-iframe", parent.document).height();
      $(".layui-layer-iframe", parent.document).height(dialogHeight - 53);
      var iframeHeight = $(
        ".layui-layer-content iframe",
        parent.document
      ).height();
      $(".layui-layer-content iframe", parent.document).height(
        iframeHeight - 53
      );
      $(".layui-layer-resize", parent.document).css("bottom", "-53px");
      //---调整窗口大小

      Controller.api.bindPrintEvent();
      //不放在bindPrintEvent方法内，防止反复弹出打印页
      $("#bill-print", parent.document).click(function () {
        Controller.api.print("bill");
      });

      $("#merge-print", parent.document).click(function () {
        Controller.api.mergePrint();
      });
      $("#export-word", parent.document).click(function () {
        Controller.api.exportWord();
      });

      Controller.api.bindEbillTabEvent();

      var index = layer.load();
      $.ajax({
        type: "get",
        url: Config.controller_url + "/edit",
        data: { ids: Config.bill_id, way: "detail" },
        success: function (data) {
          $("#fastflow-right-content #bill-edit").append($("#edit-form", data));
          $('[name^="row"]', $("#edit-form", "#fastflow-right-content")).attr(
            "disabled",
            "disabled"
          );
          $("button", $("#edit-form", "#fastflow-right-content")).addClass(
            "hidden"
          );
          Form.api.bindevent($("#edit-form"));
          $("a.btn", $("#edit-form", "#fastflow-right-content")).addClass(
            "hidden"
          );
          $(document).on("fa.event.appendfieldlist", function () {
            var textArea = $('textarea[disabled="disabled"]');
            textArea
              .closest(".form-group")
              .find(".btn-remove")
              .addClass("hidden");
            textArea
              .closest(".form-group")
              .find(".btn-dragsort")
              .addClass("hidden");
            textArea
              .closest(".form-group")
              .find(".btn-append")
              .addClass("hidden");
            textArea
              .closest(".form-group")
              .find("input")
              .attr("disabled", "disabled");
          });
          layer.close(index);
        },
        error: function (e) {
          layer.close(index);
        },
      });
    },
    viewer: function () {},
    auth: function () {
      let startRules = Config.startRules;
      if (startRules !== undefined) {
        var startText = $('textarea[name="start"]');
        startText.val(JSON.stringify(startRules));
        startText.trigger("fa.event.refreshfieldlist");
      }
      let editRules = Config.editRules;
      if (editRules !== undefined) {
        var editText = $('textarea[name="edit"]');
        editText.val(JSON.stringify(editRules));
        editText.trigger("fa.event.refreshfieldlist");
      }
      $(document).on(
        "fa.event.appendfieldlist",
        ".btn-new-start-rule",
        function (e, obj) {
          let that = this;
          Form.events.selectpicker(obj);
          Fast.api.ajax(
            {
              url: "fastflow/flow/flow/getStartAuthSelectOptionData",
              data: "",
            },
            function (data, ret) {
              let ruleBehavior = $(obj).find("select.rule-behavior");
              let ruleScope = $(obj).find("select.rule-scope");
              let ruleControl = $(obj).find("select.rule-control");
              Controller.api.buildoptions(
                ruleBehavior,
                data["behavior"],
                "table",
                [ruleBehavior.attr("value")]
              );
              Controller.api.buildoptions(ruleScope, data["scope"], "table", [
                ruleScope.attr("value"),
              ]);
              Controller.api.buildoptions(
                ruleControl,
                data["control"],
                "table",
                [ruleControl.attr("value")]
              );
              return false;
            }
          );
        }
      );
      $(document).on("change", "select.rule-scope", function () {
        let that = this;
        workerSelectPage = $(that).closest("tr").find("input.rule-worker");
        workerSelectPage.data("params", function (obj) {
          return { scope: $(that).val() };
        });

        Form.events.selectpage($(that).closest("tr"));
        workerSelectPage.selectPageClear();
      });
      $(document).on(
        "fa.event.appendfieldlist",
        ".btn-new-edit-rule",
        function (e, obj) {
          let that = this;
          Form.events.selectpicker(obj);
          Fast.api.ajax(
            {
              url: "fastflow/flow/flow/getEditAuthSelectOptionData",
              data: { flowid: Config.flow["id"] },
            },
            function (data, ret) {
              let ruleBehavior = $(obj).find("select.rule-behavior");
              let ruleSteps = $(obj).find("select.rule-steps");
              let ruleControl = $(obj).find("select.rule-control");
              Controller.api.buildoptions(
                ruleBehavior,
                data["behavior"],
                "table",
                [ruleBehavior.attr("value")]
              );
              Controller.api.buildoptions(
                ruleSteps,
                data["steps"],
                "table",
                ruleSteps.attr("value").split(",")
              );
              Controller.api.buildoptions(
                ruleControl,
                data["control"],
                "table",
                [ruleControl.attr("value")]
              );
              return false;
            }
          );
          Fast.api.ajax(
            {
              url: "fastflow/flow/flow/getFieldsWithComment",
              data: { table: Config.flow["bill"] },
            },
            function (data, ret) {
              let ruleFields = $(obj).find("select.rule-fields");
              Controller.api.buildoptions(
                ruleFields,
                data,
                "fields",
                ruleFields.attr("value").split(",")
              );
              return false;
            }
          );
        }
      );

      Form.api.bindevent($("form[role=form]"));
    },
    api: {
      bindEbillTabEvent: function () {
        $("#ebill-tab").click(function (e) {
          if (Config.ebill_id === null) {
            return;
          }
          $(".ebill-empty-hint").addClass("hidden");
          $("#ebill-content").removeClass("hidden");
          var src = $("#ebill-iframe").data("src");
          $("#ebill-iframe").attr(
            "src",
            src +
              "?action=detail" +
              "&id=" +
              Config.ebill_id +
              "&bill=" +
              Config.bill +
              "&bill_id=" +
              Config.bill_id +
              "&" +
              Config.bill_row
          );
          $("#toolbar", "#ebill").removeClass("hidden");
        });
      },
      buildoptions: function (select, data, type, value = null) {
        var html = "";
        data.forEach(function (e) {
          if (type == "fields") {
            let selected =
              $.inArray(e["field"].toString(), value) != -1 ? "selected" : "";
            html +=
              "<option value='" +
              e["field"] +
              "' " +
              selected +
              ">" +
              e["field"] +
              "(" +
              e["comment"] +
              ")" +
              "</option>";
          } else if (type == "table") {
            let selected =
              $.inArray(e["value"].toString(), value) != -1 ? "selected" : "";
            html +=
              "<option value='" +
              e["value"] +
              "' " +
              selected +
              ">" +
              e["name"] +
              "</option>";
          } else if (type == "item") {
            let selected =
              $.inArray(e.toString(), value) != -1 ? "selected" : "";
            html +=
              "<option value='" + e + "' " + selected + ">" + e + "</option>";
          }
        });
        $(select).html(html);
        if (select.data("selectpicker")) {
          select.selectpicker("refresh");
        }
        select.trigger("change");
      },
      bindevent: function () {},
      bindPrintEvent: function () {
        $("#table-print").click(function () {
          Controller.api.print("table");
        });
        $("#timeline-print").click(function () {
          Controller.api.print("timeline");
        });
        $("#ebill-print").click(function () {
          Controller.api.print("ebill");
        });
        Controller.api.bindDownloadEbillEvent();
      },
      print: function (type) {
        var originalHtml = $("body", window.document).html();
        $("#" + type + "-print").addClass("hidden");
        if (type === "table" || type === "timeline") {
          $(".detail-table").css("table-layout", "unset");
          //提取资料地址
          var fileSpan = $(".flow-file", $("." + type));
          $(fileSpan).each(function (index, item) {
            var fileUrl = $("a", $(item)).attr("href");
            var fileName = $("a", $(item)).html();
            $(item).html(
              "<label data-name='" +
                fileName +
                "'>" +
                Config.domain +
                "<span>" +
                fileUrl +
                "</span>" +
                "</label>"
            );
          });
          $("body").css("padding", "30px");
        }
        if (type == "bill") {
          $(".bill-legend").removeClass("hidden");
          $("body").css("padding", "30px");
        }
        if (type == "ebill") {
          var ebillContent = $("#ebill-iframe")
            .contents()
            .find("#ebill-content");
          var ebillImageBase64 = ebillContent
            .css("backgroundImage")
            .replace('url("', "")
            .replace('")', "");
          var ebillImage = document.createElement("img");
          var ebillWidth = ebillContent.css("width");
          var ebillHeight = ebillContent.css("height");
          $(ebillImage)
            .css("width", ebillWidth)
            .css("height", ebillHeight)
            .attr("src", ebillImageBase64)
            .attr("id", "ebill-image");
          $("#ebill-iframe").before(ebillImage);
          $("#ebill-iframe").remove();
        }
        var html = $("body", window.document).html();
        var printStart = "<!--" + type + "PrintStart-->";
        var printEnd = "<!--" + type + "PrintEnd-->";
        var printHtml = html.substr(html.indexOf(printStart));
        printHtml = printHtml.substring(0, printHtml.indexOf(printEnd));
        window.document.body.innerHTML = printHtml;
        window.print();
        //还原
        window.document.body.innerHTML = originalHtml;
        //4.4.2 还原selectpage
        Form.events.selectpage(window.document.body);
        //4.4.2 !--
        $("body").css("padding", "unset");
        Controller.api.bindPrintEvent();
        Controller.api.bindEbillTabEvent();
      },
      mergePrint: function () {
        var originalHtml = $("body", window.document).html();
        $("#table-print").addClass("hidden");
        $(".detail-table").css("table-layout", "unset");
        //提取资料地址
        var fileSpan = $(".flow-file", $(".table"));
        $(fileSpan).each(function (index, item) {
          var fileUrl = $("a", $(item)).attr("href");
          var fileName = $("a", $(item)).html();
          $(item).html(
            "<label data-name='" +
              fileName +
              "'>" +
              Config.domain +
              "<span>" +
              fileUrl +
              "</span>" +
              "</label>"
          );
        });

        $(".bill-legend").removeClass("hidden");
        var html = $("body", window.document).html();
        //table
        var tableStart = "<!--tablePrintStart-->";
        var tableEnd = "<!--tablePrintEnd-->";
        var tableHtml = html.substr(html.indexOf(tableStart));
        tableHtml = tableHtml.substring(0, tableHtml.indexOf(tableEnd));
        //bill
        var billStart = "<!--billPrintStart-->";
        var billEnd = "<!--billPrintEnd-->";
        var billHtml = html.substr(html.indexOf(billStart));
        billHtml = billHtml.substring(0, billHtml.indexOf(billEnd));

        window.document.body.innerHTML = tableHtml + billHtml;
        $("body").css("padding", "30px");
        window.print();
        //还原
        window.document.body.innerHTML = originalHtml;
        //4.4.2 还原selectpage
        Form.events.selectpage(window.document.body);
        //4.4.2 !--
        $("body").css("padding", "unset");
        Controller.api.bindPrintEvent();
        Controller.api.bindEbillTabEvent();
      },
      exportWord: function () {
        $.ajax({
          type: "get",
          url: "fastflow/flow/flow/exportWord",
          data: {
            bill: Config.bill,
            bill_id: Config.bill_id,
          },
          success: function (data) {
            if (data["code"] == 1) {
              let url = data["data"]["url"];
              let a = document.createElement("a");
              a.href = url;
              a.download = data["data"]["fileName"] + "审批详情.docx";
              a.click();
              delete a;
            } else if (data["code"] == 0) {
              Toastr.error(data["msg"]);
            }
          },
          error: function (e) {},
        });
      },
      bindDownloadEbillEvent: function () {
        require.config({
          paths: {
            jspdf: "../addons/fastflow/plugins/jsPDF-master/dist/jspdf.umd.min",
          },
        });
        require(["jspdf"], function ({ jsPDF }) {
          $("#ebill-download-pdf").on("click", function () {
            var ebillContent = $("#ebill-iframe")
              .contents()
              .find("#ebill-content");
            var contentWidth = ebillContent.css("width").replace("px", "");
            var contentHeight = ebillContent.css("height").replace("px", "");
            var a4_width = 595.28;
            var a4_height = 841.89;
            var orientation = "p"; //  l表示横版，p：纵向 （默认纵向）
            var fsWidth = ebillContent.css("width").replace("px", "");

            if (parseInt(fsWidth) >= 1122) {
              a4_width = 841.89;
              a4_height = 595.28;
              orientation = "l";
            }

            var pageData = ebillContent
              .css("backgroundImage")
              .replace('url("', "")
              .replace('")', "");
            var pageHeight = (contentWidth / a4_width) * a4_height; //pdf一页高度对应的html高度，等比缩放
            //  未生成pdf的html页面高度
            var leftHeight = contentHeight;
            //  页面偏移
            var position = 0;
            //  a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
            var imgWidth = a4_width;
            var imgHeight = (a4_width / contentWidth) * contentHeight; //需要生成的pdf总高度，等比缩放
            //  l表示横版，p：纵向 （默认纵向）
            var pdf = new jsPDF(orientation, "pt", "a4");
            //  有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
            //  当内容未超过pdf一页显示的范围，无需分页
            if (leftHeight < pageHeight) {
              pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
            } else {
              while (leftHeight > 0) {
                pdf.addImage(
                  pageData,
                  "JPEG",
                  0,
                  position,
                  imgWidth,
                  imgHeight
                );
                leftHeight -= pageHeight;
                position -= a4_height;
                //避免添加空白页
                if (leftHeight > 0) {
                  pdf.addPage();
                }
              }
            }
            var title = ebillContent.data("title");
            pdf.save(title, pdf);
          });
        });
      },
      formatter: {
        status: function (value, row, index) {
          return (
            '<a href="javascript:;" class="btn btn-xs btn-status ' +
            (value == 0 ? "btn-danger" : "btn-success") +
            '" title="点击切换" data-table-id="table" style="margin-right: 4px;font-size: 90%;">' +
            (value == 0 ? "禁用(点击启用)" : "启用(点击禁用)") +
            "</a>"
          );
        },
        designerbtn: function (value, row, index) {
          let html =
            '<a href="fastflow/flow/flow/designer?flow_id=' +
            row["id"] +
            '" class="btn btn-xs btn-info btn-dialog" title="流程设计" data-table-id="table" style="margin-right: 4px;font-size: 90%;"><i class="fa fa-list" style="margin-right: 4px;"></i>流程设计</a>';
          return html;
        },
        flowauth: function (value, row, index) {
          return (
            '<a href="fastflow/flow/flow/auth?flow_id=' +
            row["id"] +
            '" class="btn btn-xs btn-danger btn-dialog"  data-toggle="tooltip" title="流程权限配置" data-table-id="table"  data-original-title="流程权限配置" style="font-size: 90%"><i class="fa fa-lock" style="margin-right: 4px;"></i>权限配置</a>'
          );
        },
        normal: function (value, row, index) {
          return (
            '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' +
            __("Click to search %s", row["bill_name"]) +
            '" data-field="bill" data-value="' +
            row["bill"] +
            '">' +
            value +
            "</a>"
          );
        },
      },
      events: {
        status: {
          "click .btn-status": function (e, value, row, index) {
            e.stopPropagation();
            e.preventDefault();
            var that = this;
            var top = $(that).offset().top - $(window).scrollTop();
            var left = $(that).offset().left - $(window).scrollLeft() - 260;
            if (top + 154 > $(window).height()) {
              top = top - 154;
            }
            if ($(window).width() < 480) {
              top = left = undefined;
            }
            var table = $(that).closest("table");
            if (value == 0) {
              $(that).data("params", { status: 1 });
              Table.api.multi(undefined, row["id"], table, that);
            } else {
              $(that).data("params", { status: 0 });
              Layer.confirm(
                __("确定禁用吗?"),
                {
                  icon: 3,
                  title: __("Warning"),
                  offset: [top, left],
                  shadeClose: true,
                  btn: [__("OK"), __("Cancel")],
                },
                function (index) {
                  var options = table.bootstrapTable("getOptions");
                  Table.api.multi(undefined, row["id"], table, that);
                  Layer.close(index);
                }
              );
            }
          },
        },
        opendesigner: {
          "click .btn-dialog": function (e, value, row, index) {
            e.stopPropagation();
            e.preventDefault();
            var table = $(this).closest("table");
            var options = table.bootstrapTable("getOptions");
            var ids = row[options.pk];
            row = $.extend({}, row ? row : {}, { ids: ids });
            $(this).data("area", ["100%", "100%"]);
            Fast.api.open(
              Table.api.replaceurl($(this).attr("href"), row, table),
              $(this).data("original-title") || $(this).attr("title"),
              $(this).data() || {}
            );
          },
        },
      },
    },
  };
  return Controller;
});
